/***********************
 * 每一页加载动态的数量
***********************/
let loadNum = 10;
let isGettingAllNews = false,
    isGettingAllTopNews = false,
    currentPage = 1,
    newsContent = document.getElementsByClassName('news-content')[0],
    news = [],
    totalPage,
    allNews = [],
    topNewsContent = document.getElementsByClassName('top-news')[0],
    scrollTop = document.documentElement.scrollTop || document.documentElement.scrollTop || document.body.scrollTop || window.pageYOffset,
    currentModule = 'index';
    navUnderline = document.getElementsByClassName('underline')[0],
    uid = sessionStorage.getItem('id'),
    commentContent = '',
    comments = [],
    files = null,
    filesArr = [],
    formData = new FormData,
    isLiking = false;

function iniIndex() {
  loadHeadImg();
  isLogin();
  getAllNews('all');
  getTopFiveNews();
}
function changePostPage(operation) {
  if(!isGettingAllNews && !isGettingAllTopNews) {
    let body = document.getElementsByTagName('body')[0];
    if(operation == 'open') {
      let headImg = sessionStorage.getItem('headImg');
      if(headImg == 'null'){
        headImg = path + 'img/user-icon.png';
      }else {
        headImg = 'http://' + headImg;
      }
     let layerDiv = document.createElement('div');
     layerDiv.setAttribute('class','layer');
     layerDiv.innerHTML += `
      <div class="layer">
        <div class="create-news">
          <div class="close" onclick="changePostPage('close')">X</div>
          <div class="create-news-main">
            <div class="user-icon">
              <img src="${headImg}" alt="头像">
            </div>
            <div class="form">
              <form method="post" name="post-news">
                <input type="text" name="title" value="" placeholder="动态标题"/>
                <textarea name="content" placeholder="动态内容"></textarea>
                <div class="operation">
                  <div class="select-img">
                    <button class="primary large">选择图片</button>
                    <input type="file" name="img" multiple onchange="showFileInfo('news')"/>
                  </div>
                  <button type="button" class="primary large post-news" onclick="postNews()">发布</button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
     `
     document.body.appendChild(layerDiv);
    }else if(operation == 'close') {
      /* page.style.display = 'none'; */
      let layer = document.getElementsByClassName('layer')[0];
      body.removeChild(layer);
    }
  }
}
/* 获取所有动态 */
function getAllNews(method, id) {
  return new Promise((resolve, reject) => {
  /* 判断是通过用户查询还是查询全部 */
  console.log(id);
  let url,data;
  if(method == 'by-user-id') {
    url = 'http://175.178.51.126:8091/smallA/selectDiaryByUserId';
    data = {
      uid: uid,
      id: id
    }
  }else if(method == 'all') {
    url = 'http://175.178.51.126:8091/smallA/selectAllDiary';
    data = {
      uid: uid
    };
  }
  if(isGettingAllNews != true) {
    if(navUnderline != undefined) {
      navUnderline.className = 'underline index';
      currentModule = 'index';
      if(topNewsContent != undefined) {
        topNewsContent.style.opacity = '1';
      }
    }
      isGettingAllNews = true;
      newsContent.innerHTML = `<div class="loading">加载中...</div>`
      request(url ,'POST', JSON.stringify(data))
      .then(value => {
        if(value.code == 200){
          currentPage = 1;
          allNews = value.data.reverse();
          totalPage = Math.ceil(allNews.length/loadNum);
          news = divideNews();
          console.log(news);
          loadNewsDiv(news);
          if(method == 'by-user-id' && news.length != 0) {
            resolve(news[0].author)
          }
          if(news.length == 0) {
            reject('动态为空');
          }
        }
      isGettingAllNews = false;
      })
      .catch(error => {
        newsContent.innerHTML = `<div class="loading">${error}</div>`
        isGettingAllNews = false;
      })
  }
  })
}
function countCommentNum(comments) {
  let commentNum = 0;
  for(let j=0;j<comments.length;j++) {
    if(comments[j].prior == 0) {
      commentNum ++;
    }
  }
  return commentNum;
}
/* 把动态显示出来 */
function loadNewsDiv(news) {
  let commentLoad = 0; /* 记录有几个评论加载完毕 */
  for(let i=0; i<news.length;i++) {
    let newsIdData = {
      did: news[i].id
    }
    request('http://175.178.51.126:8091/smallA/selectCommentByDid','POST', JSON.stringify(newsIdData))
      .then(comments => {
        if(comments.data != null) {
          news[i].commentNum = countCommentNum(comments.data);
        }else {
          news[i].commentNum = 0;
        }
        
        commentLoad++;
      }).catch(error => {
        newsContent.innerHTML = `<div class="loading">${error}</div>`
      })
  }
  /* 等全部评论数量都加载完之后，再按顺序输出内容 */
  let loadTimer = setInterval(() => {
    if(commentLoad == news.length) {
      clearInterval(loadTimer);
      newsContent.innerHTML = '';
      if(news.length != 0) {
        for(let i=0;i<news.length;i++){
          let headImg = news[i].author.headImg,
              deleteDiv;
          if(headImg == null){
            headImg = path + 'img/user-icon.png';
          }else {
            headImg = 'http://' + headImg;
          }
          let newsDiv = document.createElement('div');
          currentModule == 'top' ? newsDiv.setAttribute('class','all-top-news') : newsDiv.setAttribute('class','news');
          newsContent.appendChild(newsDiv);
          if(currentModule == 'top' && currentPage == 1) {
            newsDiv.innerHTML += `<div class='rank'>${i+1}</div>`
          }
          if(sessionStorage.getItem('id') == news[i].author.id) {
            deleteDiv =  `<div class="delete-news danger" id="delete-${news[i].id}">删除</div>`;
          }else {
            deleteDiv =  `<div> </div>`;
          }
          newsDiv.innerHTML += `
          <div class="top-info">
            <div class="author-info">
              <div class="author-icon">
                <a href="${path}profile/others-news.html?id=${news[i].author.id}"><img src="${headImg}" alt=""></a>
              </div>
              <div class="text">
                <div class="author-name"><a href="${path}profile/others-news.html?id=${news[i].author.id}">${news[i].author.username}</a></div>
                <div class="time">发布于${news[i].updateTime}</div>
              </div>
            </div>
            ${deleteDiv}
          </div>
          `
          let newsText = document.createElement('div');
          newsText.className = 'news-text';
          newsText.innerHTML = `
          <h3>${news[i].title}</h3>
          `
          newsDiv.appendChild(newsText);
          news[i].content = toText(news[i].content);
          if(news[i].content.length > 240) {
            let newsContentText = document.createElement('p');
            newsContentText.innerHTML = news[i].content.slice(0,240) + `...<span class="load-all-text emphasis" onclick="loadAllText(${news[i].id},'open',this)">查看全文</span>`
            newsText.appendChild(newsContentText);
          }else {
            let newsContentText = document.createElement('p');
            newsContentText.innerHTML = news[i].content;
            newsText.appendChild(newsContentText);
          }
          if(news[i].images.length != 0) {
            let imagesDiv = document.createElement('div');
            imagesDiv.setAttribute('class','images');
            if(news[i].images.length <= 3) {
              for(let j=0;j<news[i].images.length;j++) {
                imagesDiv.innerHTML += `
                <img src="${path}img/image.png" data-src="${news[i].images[j].img}" onclick="openImg(this)" class="news-img"/>
                `
              }
              newsText.appendChild(imagesDiv);
            }else {
              for(let j=0;j<3;j++) {
                imagesDiv.innerHTML += `
                <img src="${path}img/image.png" data-src="${news[i].images[j].img}" onclick="openImg(this)" class="news-img"/>
                `
              }
              newsText.appendChild(imagesDiv);
              newsText.innerHTML += `<div class="load-all-image emphasis" onclick="loadAllImg(${news[i].id},'open',this)">加载全部图片</div>`
            }
          }
          if(news[i].isLike == true) {
            newsDiv.innerHTML += `
          <div class="operation">
            <div class="dislike-btn" id="like-${news[i].id}">❤ ${news[i].likesNum}</div>
            <div class="comment-btn" id="comment-${news[i].id}">🗨 ${news[i].commentNum}</div>
          </div>
          `
          }else {
            newsDiv.innerHTML += `
          <div class="operation">
            <div class="like-btn" id="like-${news[i].id}">❤ ${news[i].likesNum}</div>
            <div class="comment-btn" id="comment-${news[i].id}">🗨 ${news[i].commentNum}</div>
          </div>
          `
          }
        }
        let newsImg = document.getElementsByClassName('news-img');
        lazyLoadImg(newsImg);
        document.addEventListener('scroll',function () {
          if (timer) clearTimeout(timer);
          timer = setTimeout(() => {
            lazyLoadImg(newsImg);
          },100);
        })
      }else {
        newsContent.innerHTML = '动态为空！'
      }
      let paginationDiv = document.createElement('div');
      paginationDiv.setAttribute('class','pagination');
      totalPage = Math.ceil(allNews.length/loadNum);
      if(totalPage < 8) {
        for(let i=1;i<=totalPage;i++) {
          if(i == currentPage) {
            paginationDiv.innerHTML += `
            <span class="current-page" id="${i}">${i}</span>
            `
          }else {
            paginationDiv.innerHTML += `
            <span id="${i}">${i}</span>
            `
          }
        }
      }else {
        if(currentPage < 4) {
          for(let i=1;i<=4;i++) {
            if(i == currentPage) {
              paginationDiv.innerHTML += `
              <span class="current-page" id="${i}">${i}</span>
              `
            }else {
              paginationDiv.innerHTML += `
              <span id="${i}">${i}</span>
              `
            }
          }
          paginationDiv.innerHTML += `
            ...<span id="${totalPage}">${totalPage}</span>
            `
        }else if(currentPage > totalPage - 3) {
          paginationDiv.innerHTML += `
            <span id="1">1</span>...
            `
          for(let i=totalPage - 4;i<=totalPage;i++) {
            if(i == currentPage) {
              paginationDiv.innerHTML += `
              <span class="current-page" id="${i}">${i}</span>
              `
            }else {
              paginationDiv.innerHTML += `
              <span id="${i}">${i}</span>
              `
            }
          }
        }else if(currentPage >= 4 && currentPage <= totalPage - 3) {
          paginationDiv.innerHTML += `
            <span id="1">1</span>...
            `
            console.log(currentPage + 1);
          for(let i=currentPage - 1; i <= currentPage+1; i++) {
            if(i == currentPage) {
              paginationDiv.innerHTML += `
              <span class="current-page" id="${i}">${i}</span>
              `
            }else {
              paginationDiv.innerHTML += `
              <span id="${i}">${i}</span>
              `
            }
          }
          paginationDiv.innerHTML += `
            ...<span id="${totalPage}">${totalPage}</span>
            `
        }
      }
      newsContent.appendChild(paginationDiv);
      paginationDiv.addEventListener('click', event => {
        if(event.target.tagName == 'SPAN') {
          console.log(event.target.id);
          scrollTop = document.documentElement.scrollTop || document.documentElement.scrollTop || document.body.scrollTop || window.pageYOffset; 
          console.log(scrollTop);
          scrollTo(0, 0);
          currentPage = parseInt(event.target.id);
          console.log(currentPage)
          news = divideNews();
          newsContent.innerHTML = '<div class="loading">加载中...</div>';
          console.log(news);
          loadNewsDiv(news)
        }
      });
    }
  }, 50);
}
function loadAllText(id,operation,target) {
  let targetNewsText = target.parentElement;
  let targetNews = allNews.filter(data => {
    return data.id == id;
  })
  if(operation == 'open') {
    targetNewsText.innerHTML = targetNews[0].content + `<span class="load-all-text emphasis" onclick="loadAllText(${id}, 'close', this)">收起全文</span>`
  }else if(operation == 'close') {
    targetNewsText.innerHTML = targetNews[0].content.slice(0,240) + `...<span class="load-all-text emphasis" onclick="loadAllText(${id}, 'open', this)">查看全文</span>`
  }
}
function loadAllImg(id, operation, target) {
  let imagesDiv = target.previousElementSibling;
  let targetNews = allNews.filter(data => {
    return data.id == id;
  })
  imagesDiv.innerHTML = '';
  if(operation == 'open') {
    for(let j=0;j<targetNews[0].images.length;j++) {
      imagesDiv.innerHTML += `
      <img src="http://${targetNews[0].images[j].img}" onclick="openImg(this)"/>
      `
    }
    target.innerText = `收起图片`;
    target.setAttribute('onclick',`loadAllImg(${targetNews[0].id},'close',this)`)
  }else if(operation == 'close') {
    for(let j=0;j<3;j++) {
      imagesDiv.innerHTML += `
      <img src="http://${targetNews[0].images[j].img}" />
      `
    }
    target.innerText = `加载全部图片`;
    target.setAttribute('onclick',`loadAllImg(${targetNews[0].id},'open',this)`)  }
}
function showFileInfo(source) {
  files = document.getElementsByName('img')[0].files;
  for(let i=0;i<files.length;i++) {
    filesArr.push(files[i]);
  }
  console.log(filesArr);
  let createNewsDiv = document.getElementsByClassName('create-news')[0];
  let imgPreviewDiv = document.getElementsByClassName('img-preview')[0];
  if(imgPreviewDiv != undefined) {
    imgPreviewDiv.remove();
  }
  formData = new FormData;
  imgPreviewDiv = document.createElement('div');
  imgPreviewDiv.setAttribute('class','img-preview');
  if(source == 'news'){
    for(let i=0;i<filesArr.length;i++) {
      imgPreviewDiv.innerHTML += `<div><p>${i+1}</p><p>${filesArr[i].name}</p><p class="cancel-upload" id="remove-${i}">取消上传</p></div>` ;
      formData.append('img',filesArr[i]);
    }
  }else if(source == 'album') {
    for(let i=0;i<filesArr.length;i++) {
      imgPreviewDiv.innerHTML += `<div><p>${i+1}</p><p>${filesArr[i].name}</p><p class="cancel-upload" id="remove-${i}">取消上传</p></div>` ;
      formData.append('photo',filesArr[i]);
    }
  }
  createNewsDiv.appendChild(imgPreviewDiv);
  imgPreviewDiv.addEventListener('click', event => {
    if(event.target.className == 'cancel-upload'){
      let id = event.target.id.slice(7);
      removeFile(id);
    }
  })
  function removeFile(index) {
    console.log(index);
    filesArr.splice(index,1);
    console.log(filesArr);
    imgPreviewDiv.remove();
    formData = new FormData;
    imgPreviewDiv = document.createElement('div');
    imgPreviewDiv.setAttribute('class','img-preview');
    if(source == 'news'){
      for(let i=0;i<filesArr.length;i++) {
        imgPreviewDiv.innerHTML += `<div><p>${i+1}</p><p>${filesArr[i].name}</p><p class="cancel-upload" id="remove-${i}">取消上传</p></div>` ;
        formData.append('img',filesArr[i]);
      }
    }else if(source == 'album') {
      for(let i=0;i<filesArr.length;i++) {
        imgPreviewDiv.innerHTML += `<div><p>${i+1}</p><p>${filesArr[i].name}</p><p class="cancel-upload" id="remove-${i}">取消上传</p></div>` ;
        formData.append('photo',filesArr[i]);
      }
    }
    createNewsDiv.appendChild(imgPreviewDiv);
    imgPreviewDiv.addEventListener('click', event => {
      if(event.target.className == 'cancel-upload'){
        let id = event.target.id.slice(7);
        removeFile(id);
      }
    })
  }
}
function postNews() {
  let createNewsForm = document.getElementsByName('post-news')[0];
  if(createNewsForm.title.value != '' && createNewsForm.content.value != '' && createNewsForm.content.value != createNewsForm.title.value) {
    let postNewsBtn = document.getElementsByClassName('primary large post-news')[0];
    postNewsBtn.className = 'primary large post-news disabled';
    postNewsBtn.setAttribute('disabled','disabled');
    formData.append('uid', uid);
    formData.append('title', createNewsForm.title.value);
    formData.append('content', createNewsForm.content.value);
    request('http://175.178.51.126:8091/smallA/insertDiary','POST', formData, 'none')
      .then(value => {
        console.log(value);
        if(value.code == 200) {
          location.reload();
        }
      }).catch(error => {
        console.log(error);
      })
  }else {
    alert('请完整填写内容后再发布！且不允许发布标题和内容相同的动态！')
  }
}
/* 根据页码分割动态内容 */
function divideNews() {
  let dividedNews = [];
  console.log(currentPage);
  for(let i=loadNum*(currentPage-1),j=0; i< loadNum*(currentPage - 1) + loadNum; i++,j++) {
    if(allNews[i] != undefined) {
      dividedNews[j] = allNews[i];
    }
  }
  console.log(dividedNews);
  return dividedNews;
}
function getAllTopNews() {
  return new Promise((resolve, reject) => {
  let data = {
    uid: uid
  }
  if(isGettingAllTopNews == false){
    isGettingAllTopNews = true;
    request('http://175.178.51.126:8091/smallA/selectHotDiary','POST', JSON.stringify(data))
    .then(value => {
      console.log(value);
      if(value.code == 200){
        resolve(value);
      }else {
        reject('加载失败');
      }
      isGettingAllTopNews = false;
    })
    .catch(error => {
      console.log(error);
      isGettingAllTopNews = false;
    })
  }
})
}
function getTopFiveNews() {
  if(topNewsContent != undefined) {
    topNewsContent.innerHTML = `<h3>热榜TOP5</h3><div class="loading">加载中...</div>`
    getAllTopNews().then(value => {
      topNewsContent.innerHTML = '<h3>热榜TOP5</h3>';
      for(let i=0;i<5;i++) {
        topNewsContent.innerHTML += `
        <div onclick="getTopNewsPage()" class="top-five-news">
          <div class="up">
            <span>${i + 1}.${value.data[i].author.username}</span>
            <span>❤${value.data[i].likesNum}</span>
          </div>
          <div>${value.data[i].title}</div>
        </div>
        `
      }
    })
  }
}
function getTopNewsPage() {
  if(!isGettingAllTopNews){
    navUnderline.className = 'underline top';
    newsContent.innerHTML = `<div class="loading">加载中...</div>`;
    currentModule = 'top';
    topNewsContent.style.opacity = '0';
    getAllTopNews().then(value => {
      console.log(value);
      if(value.code == 200){
        newsContent.innerHTML = '';
        currentPage = 1;
        allNews = value.data;
        totalPage = Math.ceil(allNews.length/loadNum);
        news = divideNews();
        console.log(news);
        loadNewsDiv(news);
      }
    }).catch(error => {
      newsContent.innerHTML = error;
    })
  }
}
function search(method) {
  newsContent.innerHTML = `<div class="loading">加载中...</div>`;
  let searchContent = document.getElementsByName('search')[0];
  if(navUnderline != undefined){
    navUnderline.className = 'underline none';
  }
  currentModule = 'search';
  console.log(searchContent.value);
  const searchData = {
    uid: uid,
    key: searchContent.value
  }
  request('http://175.178.51.126:8091/smallA/selectDiary', 'POST', JSON.stringify(searchData))
    .then(value => {
      console.log(value);
      if(value.code == 200) {
        newsContent.innerHTML = '';
        currentPage = 1;
        allNews = value.data.reverse();
        if(method == 'my-news') {
          allNews = value.data.filter(data => {
            return data.author.id == sessionStorage.getItem('id');
          })
        }else if(method == 'others-news') {
          let params = new URLSearchParams(location.search);
          id = params.get('id');
          allNews = value.data.filter(data => {
            return data.author.id == id;
          })
        }
        totalPage = Math.ceil(allNews.length/loadNum);
        news = divideNews();
        loadNewsDiv(news);
      }
    })
}
function onLike(id, operation) {
  if(!isLiking) {
    id = id.slice(5);
    /* console.log(id); */
    let likeData = {
      uid: uid,
      id: id,
      ifLike: operation
    }
    isLiking = true;
    request('http://175.178.51.126:8091/smallA/likeDiary', 'POST', JSON.stringify(likeData))
      .then(value => {
        if(value.code == 200) {
          let likeBtn = document.getElementById('like-'+id);
          news = divideNews();
          let element = news.filter((data) => {
            return data.id == id;
          })
          operation == true ? likeBtn.innerHTML = '❤ ' + ++element[0].likesNum : likeBtn.innerHTML = '❤ ' + --element[0].likesNum;
          operation == true ? likeBtn.className = 'dislike-btn' : likeBtn.className = 'like-btn';
        }
      }).catch(error => {
        console.log(error);
      }).finally(() => {
        isLiking = false;
      })
  }
}
function getCommentOnIndex(id, div, operation) {
  id = {
    did: id.slice(8)
  }
  let newsDiv = div.parentElement.parentElement;
  if(operation == 'open') {
    /* 关掉所有评论 */
    let previousCommentDiv = document.getElementsByClassName('comment-content')[0];
    let previousCommentInputDiv = document.getElementsByClassName('comment')[0];
    let openCommentBtn = document.getElementsByClassName('comment-open-btn')[0];
    if(previousCommentDiv != undefined && openCommentBtn != undefined && previousCommentInputDiv != undefined) {
      previousCommentDiv.remove();
      previousCommentInputDiv.remove();
      openCommentBtn.className = 'comment-btn';
    }
    /* 打开下一个评论 */
    div.className = 'comment-open-btn';
    newsDiv.innerHTML += `
    <div class="comment">
      <textarea placeholder="发一条友善的评论..." id="comment-value-${id.did}"></textarea>
      <div class="post">
        <button class="primary large" onclick="postComment(${id.did})">发送</button>
      </div>
    </div>
    `
    commentContent = document.createElement('div');
    commentContent.setAttribute('class','comment-content');
    newsDiv.appendChild(commentContent);
    commentContent.innerHTML = `<div class="loading">加载评论中...</div>`
    request('http://175.178.51.126:8091/smallA/selectCommentByDid', 'POST', JSON.stringify(id))
      .then(value => {
        commentContent.innerHTML = '';
        if(value.code == 200) {
          comments = value.data;
          console.log(comments);
          for(let i=0;i<comments.length;i++) {
            if(comments[i].prior == 0) {
              let headImg = comments[i].author.headImg;
              if(headImg == null){
                headImg = '';
              }
              /* 显示评论 */
              showComments(headImg, comments[i].id, comments[i].author.username, comments[i].content);
            }
          }
          commentContent.addEventListener('click', event => {
            if(event.target.className == 'emphasis show-reply') {
              let showReply = event.target;
              let replyDiv = showReply.parentElement;
              showAllReply(replyDiv, true);
            }
          })
        }else {
          commentContent.innerHTML = `<div class="loading">${value.msg}</div>`
        }
      }).catch(error => {
        commentContent.innerHTML = error;
      })
  }else if(operation == 'close') {
    let commentDiv = newsDiv.getElementsByClassName('comment')[0];
    commentContent = newsDiv.getElementsByClassName('comment-content')[0];
    div.className = 'comment-btn';
    newsDiv.removeChild(commentDiv);
    newsDiv.removeChild(commentContent)
  }
}
function showAllReply(replyDiv, isFirstLevel) {
  let commentId = replyDiv.id.slice(8);
  /* 回到上一级，通过id找到这条评论下面的所有回复 */
  let replyUnderTargetComment = comments.filter(data => {
    return data.prior == commentId;
  })
  replyDiv.innerHTML = ``;
  for(let i=0;i<replyUnderTargetComment.length;i++) {
    let parentComment = comments.filter(data => {
      return commentId == data.id
    })
    parentCommentAuthor = parentComment[0].author.username;
    if(isFirstLevel){
      replyDiv.innerHTML += `
      <div class="reply-content" id="reply-${replyUnderTargetComment[i].id}">
        <a href="${path}profile/others-news.html?id=${replyUnderTargetComment[i].author.id}"><span class="emphasis">${replyUnderTargetComment[i].author.username}</span></a>
        ：${toText(replyUnderTargetComment[i].content)}
        <span class="reply-btn emphasis">回复</span>
      </div>
      `
    }else {
      replyDiv.innerHTML += `
      <div class="reply-content" id="reply-${replyUnderTargetComment[i].id}">
      <a href="${path}profile/others-news.html?id=${replyUnderTargetComment[i].author.id}"><span class="emphasis">${replyUnderTargetComment[i].author.username}</span></a>
        回复了<span class="emphasis">${parentCommentAuthor}</span>
        ：${toText(replyUnderTargetComment[i].content)}
        <span class="reply-btn emphasis">回复</span>
      </div>
      `
    }
    if(replyUnderTargetComment[i].author.id == sessionStorage.getItem('id')) {
      let targetReplyDiv = document.getElementById('reply-'+replyUnderTargetComment[i].id);
      console.log(targetReplyDiv)
      let deleteBtn = document.createElement('span');
      deleteBtn.className = 'delete-btn danger'
      deleteBtn.innerText = '删除评论';
      targetReplyDiv.appendChild(deleteBtn);
    }
    /* 如果回复里面还有回复就继续显示 */
    let reply = comments.filter(data => {
      return data.prior == replyUnderTargetComment[i].id;
    });
    if(reply.length != 0) {
      let newReplyDiv = document.createElement('div');
      newReplyDiv.className = 'sub-reply';
      newReplyDiv.id = `comment-${replyUnderTargetComment[i].id}`;
      replyDiv.appendChild(newReplyDiv);
      showAllReply(newReplyDiv, false);
    }
  }
}
function postComment(id) {
  let textarea = document.getElementById('comment-value-' + id);
  if(textarea.value != '') {
    const commentData = {
      did: id,
      uid: uid,
      content: textarea.value
    }
    request('http://175.178.51.126:8091/smallA/insertComment', 'POST', JSON.stringify(commentData))
      .then(value => {
        console.log(value);
        textarea.value = '';
        commentContent.innerHTML = '';
        let selectData = {
          did: id
        }
        commentContent.innerHTML = ''
        request('http://175.178.51.126:8091/smallA/selectCommentByDid','POST', JSON.stringify(selectData))
          .then(value => {
            if(value.code == 200) {
              comments.length = 0;
              comments = value.data;
              console.log(comments);
              for(let i=0;i<comments.length;i++) {
                if(comments[i].prior == 0) {
                  let headImg = comments[i].author.headImg;
                  if(headImg == null){
                    headImg = '';
                  }
                  /* 显示评论 */
                  let commentNumDiv = document.getElementById('comment-'+id);
                  commentNumDiv.innerText = '🗨' + countCommentNum(comments);
                  showComments(headImg, comments[i].id, comments[i].author.username, comments[i].content);
                }
              }
            }else {
              commentContent.innerHTML = '加载错误 请刷新重试！'
            }
          }).catch(error => {
            console.log(error);
          })
      })
  }else {
    alert('请输入评论后再发布！');
  }
}
function showComments(headImg, commentsId, commentsAuthor, commentsContent) {
  let reply = comments.filter(data => {
    return data.prior == commentsId;
  });
  let searchAuthorId = comments.filter(data => {
    return data.id == commentsId;
  })
  let authorId = searchAuthorId[0].author.id;
  let replyContent = '';
  if(reply.length != 0) {
    replyContent = `
    <div class="reply" id="comment-${commentsId}">
      <div class="emphasis show-reply">查看所有回复 ↓</div>
    </div>
    `;
  }
  commentsContent = toText(commentsContent);
  if(commentsAuthor == sessionStorage.getItem('username')) {
    commentContent.innerHTML += `
    <div class="comment-info">
      <div>
        <img src="http://${headImg}" class="author-icon" alt="">
      </div>
      <div class="text">
        <p id="reply-${commentsId}">
          <a href="${path}profile/others-news.html?id=${authorId}">
            <span class="emphasis">${commentsAuthor}</span>
          </a>：${commentsContent}
          <span class="reply-btn emphasis">回复</span>
          <span class="delete-btn danger">删除评论</span>
        </p>
        ${replyContent}
      </div>
    </div>`
  }else {
    commentContent.innerHTML += `
    <div class="comment-info">
      <div>
        <img src="http://${headImg}" class="author-icon" alt="">
      </div>
      <div class="text">
        <p id="reply-${commentsId}">
          <a href="${path}profile/others-news.html?id=${authorId}">
            <span class="emphasis">${commentsAuthor}</span>
          </a>：${commentsContent}
          <span class="reply-btn emphasis">回复</span>
        </p>
        ${replyContent}
      </div>
    </div>
    `
  }
}
function deleteNews(id) {
  const deleteData = {
    id: id.slice(7)
  }
  request('http://175.178.51.126:8091/smallA/deleteDiary','POST', JSON.stringify(deleteData))
    .then(value => {
      console.log(value);
      if(value.code == 200) {
        let targetDiv = document.getElementById(id);
        targetDiv.parentElement.parentElement.remove();
        deleteIndex = allNews.findIndex(data => {
          return data.id == deleteData.id;
        })
        /* 更新数组，刷新显示 */
        allNews.splice(deleteIndex,1);
        news = divideNews();
        if(news.length == 0 && currentPage != 1) {
          currentPage --;
          news = divideNews();
        }
        loadNewsDiv(news);
        confirmBox('close');
      }
    }).catch(error => {
      console.log(error);
    })
}
function changeCommentPage(operation , comment) {
    if(operation == 'open') {
      console.log(comment);
      /* 获取对应评论 */
      let headImg = comment.author.headImg;
      if(headImg == null){
        headImg = path + 'img/user-icon.png';
      }else {
        headImg = 'http://' + headImg;
      }
     let layerDiv = document.createElement('div');
     layerDiv.setAttribute('class','layer');
     layerDiv.innerHTML += `
      <div class="layer">
        <div class="create-reply">
          <div class="close" onclick="changePostPage('close')">X</div>
          <div class="comment-reply">
            <div class="author-info">
              <div>
                <img src="${headImg}" class="author-icon" alt="">
              </div>
              <div class="text">
                <div class="author-name">${comment.author.username}</div>
              </div>
            </div>
            <div class="form">
              <form method="post" name="post-reply">
                <p>${toText(comment.content)}</p>
                <textarea name="content" placeholder="发布你的回复..."></textarea>
                <div class="operation">
                  <div></div>
                  <button type="button" class="primary large" onclick="postReply(${comment.did},${comment.id})">发布</button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
     `
     document.body.appendChild(layerDiv);
    }else if(operation == 'close') {
      let layer = document.getElementsByClassName('layer')[0];
      document.body.removeChild(layer);
    }
}
function postReply(did,id) {
  let replyContent = document.getElementsByName('content')[0].value;
  let replyData = {
    uid: sessionStorage.getItem('id'),
    did: did,
    content: replyContent,
    prior: id
  }
  console.log(replyData);
  let parentCommentDiv = document.getElementById('comment-'+id);
  console.log(parentCommentDiv)
  request('http://175.178.51.126:8091/smallA/insertComment','POST', JSON.stringify(replyData))
    .then(value => {
      if(value.code == 200) {
        let selectData = {
          did: did
        }
        commentContent.innerHTML = ''
        request('http://175.178.51.126:8091/smallA/selectCommentByDid','POST', JSON.stringify(selectData))
          .then(value => {
            if(value.code == 200) {
              comments.length = 0;
              comments = value.data;
              console.log(comments);
              for(let i=0;i<comments.length;i++) {
                if(comments[i].prior == 0) {
                  let headImg = comments[i].author.headImg;
                  if(headImg == null){
                    headImg = '';
                  }
                  /* 显示评论 */
                  let commentNumDiv = document.getElementById('comment-'+did);
                  commentNumDiv.innerText = '🗨' + countCommentNum(comments);
                  showComments(headImg, comments[i].id, comments[i].author.username, comments[i].content);
                }
              }
            }else {
              commentContent.innerHTML = '加载错误 请刷新重试！'
            }
          }).catch(error => {
            console.log(error);
          })
        changeCommentPage('close');
      }else {
        alert('添加失败！')
      }
    }).catch(error => {
      console.log(error);
    })
}
function deleteComment(params) {
  params = params.replace(/\'/g,'"');
  params = JSON.parse(params);
  let idData = {
    id: params.id
  }
  request('http://175.178.51.126:8091/smallA/deleteCommentById', 'POST', JSON.stringify(idData))
    .then(value => {
      if(value.code == 200) {
        let selectData = {
          did: params.did
        }
        commentContent.innerHTML = ''
        console.log(params)
        request('http://175.178.51.126:8091/smallA/selectCommentByDid','POST', JSON.stringify(selectData))
          .then(value => {
            if(value.code == 200) {
              comments.length = 0;
              comments = value.data;
              console.log(comments);
              for(let i=0;i<comments.length;i++) {
                if(comments[i].prior == 0) {
                  let headImg = comments[i].author.headImg;
                  if(headImg == null){
                    headImg = '';
                  }
                  /* 显示评论 */
                  let commentNumDiv = document.getElementById('comment-'+params.did);
                  commentNumDiv.innerText = '🗨' + countCommentNum(comments);
                  showComments(headImg, comments[i].id, comments[i].author.username, comments[i].content);
                }
              }
            }else {
              commentContent.innerHTML = '加载错误 请刷新重试！'
            }
          })
        confirmBox('close');
      }else {
        alert(value.msg);
      }
    }).catch(error => {
      console.log(error);
    })
}
if(newsContent != undefined) {
  newsContent.addEventListener('click', event => {
    if(event.target.className == 'like-btn') {
      debounce(onLike(event.target.id, true), 500);
    }else if(event.target.className == 'dislike-btn') {
      debounce(onLike(event.target.id, false), 500);
    }else if(event.target.className == 'comment-btn') {
      console.log(event.target.getAttribute('id'));
      getCommentOnIndex(event.target.id, event.target, 'open')
    }else if(event.target.className == 'comment-open-btn') {
      getCommentOnIndex(event.target.id, event.target, 'close')
    }else if(event.target.className == 'delete-news danger') {
      confirmBox('open', event.target.id, '确认删除该动态？', '删除后不可恢复。', deleteNews);
    }else if(event.target.className == 'reply-btn emphasis') {
      let commentId;
      console.log(event.target.parentElement)
      commentId = event.target.parentElement.id.slice(6)
      console.log(comments);
      console.log(commentId)
      targetComment = comments.filter(data => {
        return data.id == commentId;
      })
      changeCommentPage('open', targetComment[0]);
    }else if(event.target.className == 'delete-btn danger') {
      let commentId = event.target.parentElement.id.slice(6);
      let targetNews = comments.filter(data => {
        return data.id == commentId;
      })
      let targetDid = targetNews[0].did;
      let params = {
        id: commentId,
        did: targetDid
      }
      params = JSON.stringify(params).replace(/\"/g,"'");
      console.log(params)
      confirmBox('open', params, '确认删除该评论？', '删除后不可恢复。', deleteComment);
    }
  });
  let status = false;/* 鼠标没有移入相应div */
  newsContent.addEventListener('mouseover', event => {
    let replyBtn, deleteBtn;
    if(event.target.id.slice(0,5) == 'reply'){
      replyBtn = event.target.getElementsByClassName('reply-btn emphasis')[0];
      deleteBtn = event.target.getElementsByClassName('delete-btn danger')[0];
      status = true;
    }else if(event.target.parentElement.id.slice(0,5) == 'reply') {
      replyBtn = event.target.parentElement.getElementsByClassName('reply-btn emphasis')[0];
      deleteBtn = event.target.parentElement.getElementsByClassName('delete-btn danger')[0];
      status = true;
    }else if(event.target.parentElement.parentElement.id.slice(0,5) == 'reply') {
      replyBtn = event.target.parentElement.parentElement.getElementsByClassName('reply-btn emphasis')[0];
      deleteBtn = event.target.parentElement.parentElement.getElementsByClassName('delete-btn danger')[0];
      status = true;
    }else {
      status = false;
    }
    if(replyBtn) {
      replyBtn.style.display = 'inline-block';
    }
    if(deleteBtn) {
      deleteBtn.style.display = 'inline-block';
    }
  })
  newsContent.addEventListener('mouseout', event => {
    let replyBtn, deleteBtn;
    if(event.target.id.slice(0,5) == 'reply'){
      replyBtn = event.target.getElementsByClassName('reply-btn emphasis')[0];
      deleteBtn = event.target.getElementsByClassName('delete-btn danger')[0];
      status = false;
    }else if(event.target.parentElement.id.slice(0,5) == 'reply') {
      replyBtn = event.target.parentElement.getElementsByClassName('reply-btn emphasis')[0];
      deleteBtn = event.target.parentElement.getElementsByClassName('delete-btn danger')[0];
      status = false;
    }else if(event.target.parentElement.parentElement.id.slice(0,5) == 'reply') {
      replyBtn = event.target.parentElement.parentElement.getElementsByClassName('reply-btn emphasis')[0];
      deleteBtn = event.target.parentElement.parentElement.getElementsByClassName('delete-btn danger')[0];
      status = false;
    }
    if(!status){
      if(replyBtn) {
        replyBtn.style.display = 'none';
      }
      if(deleteBtn) {
        deleteBtn.style.display = 'none';
      }
    }    
  })
}